<template>
  <div id="home">
    <!-- 搜索框 -->
    <van-search
      v-model="searchInfo"
      placeholder="请输入搜索关键词"
      shape="round"
      @search="onSearch"
    >
    </van-search>
    <!-- 轮播图组件 -->
    <itemSwipe :items="items" />
    <van-cell icon="shop-collect-o" title="发现好货"></van-cell>
    <!-- 商品列表组件 -->
    <itemGrid :items="items" />
  </div>
</template>

<script>
import itemGrid from "../../components/common/itemGrid"
import itemSwipe from "./components/itemSwipe"
import { axios, API_URL } from "../../api"
import { Search, Tab, Tabs, Cell } from "vant"
export default {
  components: {
    itemGrid,
    itemSwipe,
    [Search.name]: Search,
    [Tab.name]: Tab,
    [Tabs.name]: Tabs,
    [Cell.name]: Cell
  },
  data() {
    return {
      searchInfo: "",
      items: []
    }
  },
  methods: {
    onSearch() {
      this.$router.push({
        name: "searchResult",
        query: {
          item_name: this.searchInfo
        }
      })
    }
  },
  mounted: function() {
    // 获取商品item_id
    axios
      .get(API_URL + "item/search", {})
      .then(response => {
        let item_ids = response.data.item_ids

        // 通过item_id获取商品信息
        item_ids.forEach(id => {
          axios
            .get(API_URL + "items/" + id, {})
            .then(response => {
              let item = {}
              item.name = response.data.name
              item.current_price = response.data.current_price
              item.original_price = response.data.original_price
              item.in_stock = response.data.in_stock
              item.info = response.data.info
              item.sales = response.data.sales
              item.shop_id = response.data.shop_id
              item.images = response.data.images
              item.item_id = id
              this.items.push(item)
            })
            .catch(err => {
              console.error(err)
            })
        })
      })
      .catch(err => {
        console.error(err)
      })
  }
}
</script>
